package com.fox.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fox.domain.ResponseResult;
import com.fox.config.constant.SystemConstants;
import com.fox.domain.dto.AddArticleDto;
import com.fox.domain.dto.ArticleDto;
import com.fox.domain.entity.Article;
import com.fox.domain.entity.ArticleTag;
import com.fox.domain.entity.Category;
import com.fox.domain.vo.*;
import com.fox.mapper.ArticleMapper;
import com.fox.service.ArticleService;
import com.fox.service.ArticleTagService;
import com.fox.service.CategoryService;
import com.fox.utils.BeanCopyUtils;
import com.fox.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article>
        implements ArticleService {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticleTagService articleTagService;


    @Override
    public ResponseResult hotArticleList() {
        // 查询热门文章 封装成ResponseResult 返回
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //必须是正式文章
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        //按照浏览量进行排序（降序）
        queryWrapper.orderByDesc(Article::getViewCount);
        //最多查询10条
        Page<Article> page = new Page<>(1,10);
        page(page,queryWrapper);
        List<Article> articles = page.getRecords();

        List<HotArticleVo> articleVos = BeanCopyUtils.copyBeanList(articles, HotArticleVo.class);
        return ResponseResult.okResult(articleVos);
    }

    @Override
    public ResponseResult articleList(Integer pageNum, Integer pageSize, Long categoryId) {
        //查询条件
        LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //如果有categoryId就要传入，没有则不传
        lambdaQueryWrapper.eq(Objects.nonNull(categoryId)&&categoryId>0,
                Article::getCategoryId,categoryId);
        //状态是正式发布的
        lambdaQueryWrapper.eq(Article::getStatus,SystemConstants.ARTICLE_STATUS_NORMAL);
        // 对isTop进行降序
        lambdaQueryWrapper.orderByDesc(Article::getIsTop);

        //分页查询
        Page<Article> page = new Page<>(pageNum,pageSize);
        page(page,lambdaQueryWrapper);


        // 查询categoryName
        List<Article> articles = page.getRecords();
        //使用Article的categoryId将category类的categoryName赋值给article
        for (Article article:articles) {
            Category category = categoryService.getById(article.getCategoryId());
            article.setCategoryName(category.getName());
        }
        //封装查询结果
        List<ArticleListVo> articleListVos = BeanCopyUtils.copyBeanList(articles, ArticleListVo.class);
        PageVo pageVo = new PageVo(articleListVos,page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult getArticleDetail(Long id) {
        //根据id查询文章
        Article article = getById(id);
        // 从redis中获取viewCount
        Integer cacheMapValue = redisCache.getCacheMapValue(SystemConstants.ARTICLE_VIEW_COUNT_KEY, id.toString());
        article.setViewCount(cacheMapValue.longValue());

        ArticleDetailVo articleDetailVo = BeanCopyUtils.copyBean(article, ArticleDetailVo.class);
        //获取categoryName
        Category category = categoryService.getById(articleDetailVo.getCategoryId());
        if (category != null) {
            articleDetailVo.setCategoryName(category.getName());
        }
        return ResponseResult.okResult(articleDetailVo);
    }

    @Override
    public ResponseResult updateViewCount(Long id) {
        // 更新redis中对应的id的浏览量
        redisCache.incrementCacheMapValue(SystemConstants.ARTICLE_VIEW_COUNT_KEY,id.toString(),1);
        return ResponseResult.okResult();
    }

    @Override
    @Transactional
    public ResponseResult add(AddArticleDto articleDto) {
        //添加 博客
        Article article = BeanCopyUtils.copyBean(articleDto, Article.class);
        save(article);
        List<ArticleTag> articleTags = new ArrayList<>();
        for (Long tagId : articleDto.getTags()) {
            ArticleTag articleTag = new ArticleTag(articleDto.getId(), tagId);
            articleTags.add(articleTag);
        }
        //添加 博客和标签的关联
        articleTagService.saveBatch(articleTags);
        return ResponseResult.okResult();
    }

    @Override
    public PageVo selectArticlePage(Article article, Integer pageSize, Integer pageNum) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(article.getTitle()),Article::getTitle,article.getTitle());
        queryWrapper.like(StringUtils.hasText(article.getSummary()),Article::getSummary,article.getSummary());
        Page<Article> page = new Page<>();
        //设置当前页码
        page.setCurrent(pageNum);
        //设置每页记录数
        page.setSize(pageSize);
        page(page,queryWrapper);

        //转换为VO对象
        List<Article> articles = page.getRecords();
        List<SysArticleListVo> sysArticleListVos = BeanCopyUtils.copyBeanList(articles, SysArticleListVo.class);
        PageVo pageVo = new PageVo(sysArticleListVos,page.getTotal());
        return pageVo;
    }

    @Override
    public SysArticleVo getInfo(Long id) {
        Article article = getById(id);
        //要进行联表查询
        LambdaQueryWrapper<ArticleTag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ArticleTag::getArticleId,id);
        List<ArticleTag> articleTags = articleTagService.list(queryWrapper);
        //将articleTags中的tag取出来
        List<Long> tags = new ArrayList<>();
        for (ArticleTag articleTag : articleTags) {
            tags.add(articleTag.getTagId());
        }
        SysArticleVo articleVo = BeanCopyUtils.copyBean(article, SysArticleVo.class);
        articleVo.setTags(tags);
        return articleVo;
    }

    @Override
    public void edit(ArticleDto articleDto) {
        Article article = BeanCopyUtils.copyBean(articleDto, Article.class);
        //跟新之后都是正式文章
        article.setStatus(String.valueOf(SystemConstants.ARTICLE_STATUS_NORMAL));
        //跟新博客信息
        updateById(article);
        //删除原有的 标签和博客的关联(因为你更新之后，标签和文章的关系可能就变化了)
        LambdaQueryWrapper<ArticleTag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ArticleTag::getArticleId,article.getId());
        articleTagService.remove(queryWrapper);
        //添加新的博客和标签的关联关系
        List<ArticleTag> articleTags = new ArrayList<>();
        for (Long tagId : articleDto.getTags()) {
            ArticleTag articleTag = new ArticleTag(articleDto.getId(),tagId);
            articleTags.add(articleTag);
        }
        articleTagService.saveBatch(articleTags);
    }
}
